package com.kkb.merchant.center.server.service;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.kkb.merchant.center.api.TemplateInfoService;
import com.kkb.merchant.center.common.pojo.BrandInfo;
import com.kkb.merchant.center.common.pojo.TemplateInfo;
import com.kkb.merchant.center.server.mappers.BrandInfoMapper;
import com.kkb.merchant.center.server.mappers.TemplateInfoMapper;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.NumberUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class TemplateInfoServiceImpl implements TemplateInfoService {

    @Autowired
    private TemplateInfoMapper templateInfoMapper;

    @Autowired
    private BrandInfoMapper brandInfoMapper;


    @Override
    public PageInfo<TemplateInfo> getTemplate(Integer page, Integer size) {
        PageHelper.startPage(page,size);
        List<TemplateInfo> templateInfos = templateInfoMapper.selectAll();
        PageInfo<TemplateInfo> pageInfo = new PageInfo<>(templateInfos);
        return pageInfo;
    }

    /**
     * 关联品牌和属性
     * @param record
     * @return
     */
    @Override
    public int updateTemplateInfo(TemplateInfo record) {
        String brandids = record.getBrands();
        if(StringUtils.isNotEmpty(brandids)){
            String[] brandis = StrUtil.split(brandids,",");
            List<Map<String,Object>> result = new ArrayList<>();
            for(int i=0;i<brandis.length;i++){
                Map<String,Object> brand = new HashMap<>();
                int id = NumberUtil.parseInt(brandis[i]);
                BrandInfo brandInfo = brandInfoMapper.selectByPrimaryKey(id);
                brand.put("id",id);
                brand.put("brandName",brandInfo.getBrandName());
                result.add(brand);
            }
            record.setBrands(JSONArray.toJSONString(result));
        }

        return templateInfoMapper.updateByPrimaryKeySelective(record);
    }

    /**
     * 获取分类模版
     * @param id
     * @return
     */
    @Override
    public TemplateInfo getBrandsAndAttr(Integer id) {
        Example example = new Example(TemplateInfo.class);
        example.createCriteria().andEqualTo("categoryId",id);

        return templateInfoMapper.selectOneByExample(example);
    }
}
